<template>
  <div>
    <div class="search">
      <a-form-model
        layout="inline"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-space>
          <a-button type="primary" @click="add">
            <a-icon type="plus" />添加
          </a-button>
          <a-button title="" type="primary" @click="exportExcel">
            <a-icon type="export" />execl导出
          </a-button>
        </a-space>
        <div>
          <a-form-model-item
            label="菜单名称"
            labelAlign="right"
            prop="menuName"
          >
            <a-input v-model="queryParam.menuName" />
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary" @click="query">查询</a-button>
          </a-form-model-item>
        </div>
      </a-form-model>
    </div>
    <a-table
      rowKey="id"
      :columns="columns"
      :pagination="false"
      :data-source="data"
      @change="onChange"
      :scroll="{ x: 1800, y: 820 }"
    >
      <span slot="type" slot-scope="item"> {{ item ? '菜单' : '按钮' }}</span>
      <span slot="boolean" slot-scope="item"> {{ item ? '是' : '否' }}</span>
      <span slot="menuIcon" slot-scope="menuIcon">
        <a-icon v-if="menuIcon" :type="menuIcon" />{{
          menuIcon ? '' : '-'
        }}</span
      >
      <span slot="nullformat" slot-scope="string"> {{ string || '-' }}</span>
      <span slot="time" slot-scope="time"> {{ time | formatTimer }}</span>
      <span slot="operation" slot-scope="menu">
        <a-space>
          <!-- <a-button @click="detail(menu)"
                  type="">详情</a-button> -->
          <a-button @click="edit(menu)" type="primary">
            <a-icon type="edit" />
          </a-button>
          <a-button @click="assignmentApi(menu.id)">
            <a-icon type="api" />
          </a-button>
          <a-button v-if="menu.isMenu" @click="add(menu)" type="dashed">
            <a-icon type="plus" />
          </a-button>
          <a-popconfirm
            title="确定删除？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="del(menu.id)"
          >
            <a-button type="danger">
              <a-icon type="delete" />
            </a-button>
          </a-popconfirm>
        </a-space>
      </span>
    </a-table>
    <a-modal
      :title="api.title"
      :visible="api.visible"
      :confirm-loading="api.confirmLoading"
      :footer="null"
      :width="800"
      @afterClose="apiHandlerCompleted"
      @cancel="apiHandlerCompleted"
    >
      <!-- 按钮分配穿梭框 -->
      <a-transfer
        :list-style="{
          width: '300px',
          height: '500px'
        }"
        show-search
        :data-source="interfaces"
        :titles="['未拥有接口', '已拥有接口']"
        :target-keys="targetKeys"
        @change="apiHandleChange"
        :render="item => item.title"
      />
    </a-modal>
    <a-modal
      :title="modal.title"
      :visible="modal.visible"
      :confirm-loading="modal.confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="entity"
        :model="form"
        :rules="rules"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-model-item label="类型" labelAlign="right" prop="isMenu">
          <a-radio-group
            name="menu"
            :default-value="true"
            v-model="form.isMenu"
          >
            <a-radio :value="true">
              菜单
            </a-radio>
            <a-radio :value="false">
              按钮
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="父菜单" labelAlign="right">
          <a-select
            show-search
            allowClear
            :disabled="fixed"
            :value="form.menuParentText"
            style="width: 200px"
            @search="menuListOptions"
            @change="menuParentSelectChange"
          >
            <a-select-option
              v-for="menu in menuListOption"
              :key="menu.key"
              :value="menu.text"
            >
              {{ menu.text }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          :label="form.isMenu ? '菜单名称' : '按钮名称'"
          labelAlign="right"
          prop="menuName"
        >
          <a-input v-model="form.menuName" />
        </a-form-model-item>
        <a-form-model-item
          :label="form.isMenu ? '菜单编码' : '按钮编码'"
          labelAlign="right"
          prop="menuCode"
        >
          <a-input v-model="form.menuCode" />
        </a-form-model-item>
        <a-form-model-item
          v-if="form.isMenu"
          label="菜单路由"
          labelAlign="right"
          prop="menuRouter"
        >
          <a-input v-model="form.menuRouter" />
        </a-form-model-item>
        <a-form-model-item
          v-if="form.isMenu"
          label="菜单组件"
          labelAlign="right"
          prop="menuComponent"
        >
          <a-input v-model="form.menuComponent" />
        </a-form-model-item>
        <a-form-model-item
          v-if="form.isMenu"
          label="排序号"
          labelAlign="right"
          prop="sortNo"
        >
          <a-input v-model="form.sortNo" />
        </a-form-model-item>
        <a-form-model-item
          :label="form.isMenu ? '菜单图标' : '按钮图标'"
          labelAlign="right"
          prop="menuIcon"
        >
          <a-select
            show-search
            allowClear
            :value="form.menuIcon"
            option-filter-prop="children"
            style="width: 200px"
            @change="selectChange"
            :filter-option="filterOption"
          >
            <a-select-option
              v-for="icon in iconOptions"
              :key="icon.key"
              :value="icon.key"
            >
              <a-icon v-if="icon.key" :type="icon.key"></a-icon>
              <span v-if="icon.key"> {{ icon.key }}</span>
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="是否禁用" labelAlign="right" prop="disable">
          <a-radio-group
            name="disable"
            :default-value="false"
            v-model="form.disable"
          >
            <a-radio :value="true">
              是
            </a-radio>
            <a-radio :value="false">
              否
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
const columns = [
  {
    title: '菜单名称',
    dataIndex: 'menuName',
    key: 'menuName',
    fixed: 'left'
  },
  { title: '菜单编码', dataIndex: 'menuCode', width: 200, key: 'menuCode' },
  {
    title: '菜单图标',
    dataIndex: 'menuIcon',
    key: 'menuIcon',
    scopedSlots: { customRender: 'menuIcon' }
  },
  {
    title: '菜单路由',
    dataIndex: 'menuRouter',
    key: 'menuRouter',
    scopedSlots: { customRender: 'nullformat' }
  },
  {
    title: '菜单组件',
    dataIndex: 'menuComponent',
    key: 'menuComponent',
    scopedSlots: { customRender: 'nullformat' },
    width: 240
  },
  { title: '排序号', dataIndex: 'sortNo', key: 'sortNo' },
  {
    title: '类型',
    dataIndex: 'isMenu',
    key: 'isMenu',
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '是否禁用',
    dataIndex: 'disable',
    key: 'disable',
    scopedSlots: { customRender: 'boolean' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    scopedSlots: { customRender: 'time' }
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    scopedSlots: { customRender: 'time' }
  },
  {
    title: '操作',
    key: 'operation',
    scopedSlots: { customRender: 'operation' },
    width: 240,
    fixed: 'right'
  }
]
import VueIcon from '@ant-design/icons-vue'
import {
  menuListQuery,
  getMenu,
  updateMenu,
  menuListByName,
  createMenu,
  deleteMenu
} from '@a/sysMenu'
import {
  sysInterfaceGetAll,
  sysInterfaceGetAllocated,
  sysMenuInterfaceDelete,
  sysMenuInterfaceSave
} from '@a/sysInterface'
import { formatTimer } from '@u/utils'
export default {
  data() {
    return {
      icons: VueIcon.definitions.collection,
      fixed: false,
      queryParam: {
        menuName: null
      },
      // pageQuery: {
      //   showSizeChanger: true,
      //   hideOnSinglePage: true,
      //   showQuickJumper: true,
      //   pageSizeOptions: ['10', '20', '50', '100'],
      //   total: 0,
      //   current: 1,
      //   defaultCurrent: 1,
      //   pageSize: 10,

      // },
      modal: {
        title: '',
        visible: false,
        confirmLoading: false
      },
      data: [],
      columns,
      rules: {
        menuName: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        menuCode: [
          { required: true, message: '请输入菜单编码', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        sortNo: [
          { pattern: /^\d+$/, message: '排序号只能是数字', trigger: 'blur' }
        ]
      },
      form: {
        children: null,
        createTime: null,
        deleted: false,
        disable: false,
        id: null,
        isMenu: true,
        level: null,
        menuCode: null,
        menuComponent: null,
        menuIcon: null,
        menuName: null,
        menuParentText: null,
        menuParentId: null,
        menuRouter: null,
        sortNo: 99,
        updateTime: null,
        version: 0
      },
      iconOptions: [
        { key: 'api', text: 'api' },
        { key: 'setting', text: 'setting' },
        { key: 'plus', text: 'plus' },
        { key: 'export', text: 'export' },
        { key: 'dashboard', text: 'dashboard' }
      ],
      menuListOption: [],
      targetKeys: [],
      buttons: [],
      interfaces: [],
      currentId: null,
      api: {
        title: '接口信息',
        visible: false,
        confirmLoading: false
      }
    }
  },
  created() {
    this.loadIcon()
    this.query()
    this.menuListOptions()
  },
  methods: {
    loadIcon() {
      this.iconOptions = Object.values(VueIcon.definitions.collection)
        .filter(t => t)
        .filter(icon => icon.theme == 'outline')
        .map(icon => {
          return {
            key: icon.name,
            text: icon.name
          }
        })
    },
    onChange(pageQuery) {
      this.pageQuery = pageQuery
      this.query()
    },
    query() {
      menuListQuery(this.queryParam).then(res => {
        if (res.code === 200) {
          this.data = res.data
        }
      })
    },
    add(item) {
      if (item) {
        this.form.menuParentText = item.menuName
        this.form.menuParentId = item.id
      }
      this.modal.visible = true
      this.modal.title = '新增'
      console.log('添加数据')
    },
    exportExcel() {
      console.log('导出Excel')
    },
    detail(menu) {
      this.form = menu
      this.menuListOptions(menu.menuParentText)
      this.modal.visible = true
      this.modal.title = '详情'
      console.log('详情' + menu)
    },
    edit(item) {
      this.menuListOptions(item.menuParentText)
      getMenu(item.id).then(res => {
        if (res.code === 200) {
          this.form = res.data
          this.modal.visible = true
          this.modal.title = '编辑'
          console.log(this.modal)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    del(id) {
      deleteMenu(id).then(res => {
        if (res.code === 200) {
          this.$message.info('删除成功')
          this.query()
        } else {
          this.$message.error(res.msg)
        }
      })
      console.log('删除' + id)
    },
    handleOk() {
      this.$refs.entity.validate(valid => {
        if (valid) {
          if (this.modal.title === '编辑') {
            updateMenu(this.form).then(res => {
              if (res.code === 200) {
                this.$message.info('更新成功')
                this.handleCancel()
                this.query()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            createMenu(this.form).then(res => {
              if (res.code === 200) {
                this.$message.info('更新成功')
                this.handleCancel()
                this.query()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
          console.log('modal ok')
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.modal.visible = false
      this.resetForm()
      this.menuListOptions()
      console.log('modal cancel')
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].componentOptions.propsData.type
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    selectChange(value) {
      this.form.menuIcon = value
    },
    menuParentSelectChange(value, option) {
      console.log(option)
      this.form.menuParentText = value
      this.form.menuParentId = option.data.key
      this.menuListOptions()
    },
    menuListOptions(value) {
      menuListByName(value || '').then(res => {
        if (res.code === 200) {
          this.menuListOption = res.data.map(menu => ({
            text: menu.menuName,
            key: menu.id
          }))
        }
      })
    },
    resetForm() {
      let that = this
      setTimeout(function() {
        that.form = {
          children: null,
          createTime: null,
          deleted: false,
          disable: false,
          id: null,
          isMenu: true,
          level: null,
          menuCode: null,
          menuComponent: null,
          menuIcon: null,
          menuName: null,
          menuParentId: null,
          menuRouter: null,
          sortNo: 99,
          updateTime: null,
          version: 0
        }
      }, 500)
    },
    assignmentApi(id) {
      // 获取全部按钮
      sysInterfaceGetAll().then(res => {
        if (res.code === 200) {
          let interfaces = []
          res.data.forEach(element => {
            interfaces.push({
              key: element.id + '',
              title: element.interfaceName,
              description: element.interfaceName
            })
          })
          sysInterfaceGetAllocated(id).then(res => {
            if (res.code === 200) {
              let targetKeys = []
              res.data.forEach(e => {
                targetKeys.push(e.id + '')
              })
              this.interfaces = interfaces
              this.targetKeys = targetKeys
              this.currentId = id
              this.api.visible = true
            }
          })
        }
      })
    },
    apiHandleChange(targetKeys, direction, moveKeys) {
      let params = {
        menuId: this.currentId,
        interfaces: moveKeys
      }
      if (direction === 'right') {
        // 分配权限
        sysMenuInterfaceSave(params).then(res => {
          if (res.code !== 200) {
            this.$message.error('分配失败！')
            this.assignmentApi(this.currentId)
          }
        })
      } else {
        // 收回权限
        sysMenuInterfaceDelete(params).then(res => {
          if (res.code !== 200) {
            this.$message.error('分配失败！')
            this.assignmentApi(this.currentId)
          }
        })
      }
      this.targetKeys = targetKeys
    },
    apiHandlerCompleted() {
      this.targetKeys = []
      this.interfaces = []
      this.currentId = null
      this.api.visible = false
    }
  },
  filters: {
    formatTimer
  }
}
</script>
<style>
.search .ant-form {
  padding: 10px 50px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
